package org.jupiter.blog.authentic.handler;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;
import org.jupiter.blog.authentic.constant.AuthenticConstant;
import org.jupiter.blog.authentic.service.TokenService;
import org.jupiter.blog.redis.component.SpringRedisRepository;

import java.io.IOException;
import java.time.Duration;
import java.util.List;

@Component
public class LoginSuccessHandler implements AuthenticationSuccessHandler {

	@Autowired
	private TokenService tokenService;

	@Autowired
	private SpringRedisRepository redisRepository;

	@Override
	public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
			Authentication authentication) throws IOException {
		UserDetails user = (UserDetails) authentication.getPrincipal();
		String token = tokenService.generateToken(user);
		// 假设权限就是角色集合
		List<String> authorities = user.getAuthorities().stream()
				.map(GrantedAuthority::getAuthority)
				.toList();

		// 存入 Redis，按 token 存储用户名并设置过期
		String tokenKey = AuthenticConstant.AUTH_TOKEN_PREFIX + token;
		redisRepository.set(tokenKey, user.getUsername(), 60);

		response.setContentType("application/json;charset=UTF-8");
		response.getWriter().write("{\"code\":200,\"token\":\"" + token + "\"}");
	}
}
